const router = require('koa-router')();
const { sequelize } = require('../common/dbs')
var Sequelize = require('sequelize')
const commentModel = require("../models/comment")
const commentInfo = commentModel(sequelize);

const replyModel = require("../models/reply")
const replyInfo = replyModel(sequelize);
var md5 = require('md5-node');
const BASE_AVATAR = 'https://cravatar.cn/avatar/'

// 回复评论
router.post('/reply', async (ctx) => {
    try {
        ctx
            .validateBody("content")
            .required("内容不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("comment_id")
            .required("评论id不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("from_name")
            .required("评论人昵称不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("to_name")
            .required("回复人昵称不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let b = {
            topic_id: reqBody.topic_id, //文章id
            id: getuuid(),
            comment_id: reqBody.comment_id,
            content: reqBody.content,
            from_name: reqBody.from_name,
            to_name: reqBody.to_name,
            role_name: reqBody.role_name,
            email: reqBody.email,
            avatar: BASE_AVATAR + md5(reqBody.email) + '?d=mp&s=40'
        }
        // 新增
        requestData = await replyInfo.create(b)
        if (requestData) {
            ctx.success('回复成功')
        } else {
            ctx.fail(0, '回复失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

// 评论文章
router.post('/add', async (ctx) => {
    try {
        ctx
            .validateBody("topic_id")
            .required("内容id不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("from_name")
            .required("评论人昵称不能为空")
            .isString()
            .trim()

        ctx
            .validateBody("email")
            .required("邮箱不能为空,用于接受回复消息")
            .isString()
            .trim()
        ctx
            .validateBody("content")
            .required("内容不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null


        let b = {
            topic_id: reqBody.topic_id, //文章id
            pid: reqBody.pid ? reqBody.pid : 0, //文章id
            from_name: reqBody.from_name, //评论人名称
            email: reqBody.email, //邮箱
            url: reqBody.url || '#', //网站
            to_name: reqBody.to_name,
            to_email: reqBody.to_email,
            to_id: reqBody.to_id,
            role_name: reqBody.role_name,
            content: reqBody.content,
            avatar: BASE_AVATAR + md5(reqBody.email) + '?d=mp&s=40'
        }

        // 新增
        requestData = await commentInfo.create(b)
        if (requestData) {
            ctx.success(requestData)
        } else {
            ctx.fail(0, '评论失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

// 删除
router.post('/del', async (ctx) => {
    try {
        ctx
            .validateBody("id")
            .required("id不能为空")
            .isString()
            .trim()

        let requestData = await commentInfo.destroy({
            where: {
                id: ctx.vals.id
            }
        })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '文章已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})



const replyHasMany = commentInfo.hasMany(replyInfo, { foreignKey: 'comment_id', sourceKey: 'id', as: 'children', });

// 查询列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        if (!reqQuery.cId) {
            ctx.fail(0, '文章id不能为空')
            return
        }
        // 多对多 回复和用户关联
        let reData = await commentInfo.findAndCountAll(
            {
                where: {
                    topic_id: reqQuery.cId
                },
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC'],
                    ['pid', 'DESC'],
                ],
                attributes: {   // exclude排除
                    exclude: ['updated_at', 'deleted_at','email','topic_id'],
                },

                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
            }
        );

        let newData = JSON.parse(JSON.stringify(reData.rows))
        reData.rows = initTree(newData)

        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})
// 后台查询列表
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;

        // 多对多 回复和用户关联
        let reData = await commentInfo.findAndCountAll(
            {
                // where: {
                //     topic_id: reqQuery.cId
                // },
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                attributes: {   // exclude排除
                    exclude: ['updated_at', 'deleted_at'],
                },
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
            }
        );
        let newData = JSON.parse(JSON.stringify(reData.rows))
        reData.rows = initTree(newData)
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})

function getData(data) {
    var r = new Promise((resolve, reject) => {
        data.rows.map(item => {
            item.dataValues['comment_name'] = item['user'].dataValues.name
            delete item.dataValues.user
        })
        if (data) {
            resolve(data);
        } else {
            reject(data);
        }
    });
    return r
}


module.exports = router.routes();

/**
 * 生成tree
 * @param parent_id 父id
 */
const initTree = (jsonArray, parent_id = 0) => {
    // jsonArray 变量数据
    // 第一次以后：根据id去查询parent_id相同的（相同为子数据）
    // 第一次：查找所有parent_id为0的数据组成第一级
    const children = jsonArray.filter(item => item.pid == parent_id)
    // // 第一次：循环parent_id为0数组
    return children.map(item => ({
        ...item,
        // 当前存在id（id与parent_id应该是必须有的）调用initTree() 查找所有parent_id为本id的数据
        // childs字段写入
        children: initTree(jsonArray, item.id)
    }))
}

function getuuid() {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
